//
//  CHSingleButtonView.swift
//  CHSimpleUI
//
//  Created by cyptt on 2023/4/20.
//

import UIKit
public enum CH_SINGLE_BUTTON_TITLE_LOCAL0 : Int {
    case left = 0  //左边
    case center = 1 //中间
    case right = 2 //中间

}

public struct CHSIGLE_CHIOSE_CONST{
    public static  var defaultColor:UIColor =  UIColor.init(red: 67/255.0, green: 67/255.0, blue: 67/255.0, alpha: 1)
    public static var selectedColor:UIColor = UIColor.init(red: 41/255.0, green: 199/255.0, blue: 172/255.0, alpha: 1)
    public static var lineColor:UIColor = selectedColor
    public static var lineW:CGFloat = 0
    public static var lineH:CGFloat = 2
    public static var defFont:UIFont = UIFont.systemFont(ofSize: 17)
    public static var selFont:UIFont = UIFont.systemFont(ofSize: 17)
    
    
    public static var defBgColor:UIColor =  UIColor.white
    public static var selectBgColor = UIColor.init(red: 67/255.0, green: 67/255.0, blue: 67/255.0, alpha: 1)
}
public class CHSingleChioseViewSwift: UIView {
    
    
    private var selfW:CGFloat = 0
    private var selfH:CGFloat = 0
    private var isShowView:Bool = false
    
    private var titleLocal:CH_SINGLE_BUTTON_TITLE_LOCAL0 = .center
    private var titleArr:[String] = []
    private var defaultColor:UIColor =  CHSIGLE_CHIOSE_CONST.defaultColor
    private var selectedColor:UIColor = CHSIGLE_CHIOSE_CONST.selectedColor
    private var defFont:UIFont = CHSIGLE_CHIOSE_CONST.defFont
    private var selFont:UIFont = CHSIGLE_CHIOSE_CONST.selFont
    
    private var lineColor:UIColor = CHSIGLE_CHIOSE_CONST.lineColor
    private var currentBtn:UIButton?
    private var clickItemCallBack:((_ index:Int,_ title:String?) -> ())?
    
    private let SigleChioseTAG:Int = 100000;
    
    
    private var lineWith:CGFloat = CHSIGLE_CHIOSE_CONST.lineW
    

    private var lineH:CGFloat = CHSIGLE_CHIOSE_CONST.lineH
    
    private var itemW:CGFloat?
    
    private var defIndex:Int = 0
    

    
    private var buttonArr:[UIButton] = []
    private var lineArr:[UILabel] = []
    public override init(frame: CGRect) {
        super.init(frame: frame)
    
        self.initViews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /*
     @param titleArr 请title个数数组
     @param local 位置
     @param defaultColor 默认颜色
     @param selectedColor 选中颜色
     @param defFont 正常字体
     @param selFont 选中字体
     @param lineColor 线条颜色
     @param lineW 线条宽度 不设置和字同宽
     @param lineH 线条高度 默认2
     @param itemW 每个item宽度，不设置默认等分
     @param defIndex 默认选择第几个
     */
    public func setTitleArr(titleArr:[String],local:CH_SINGLE_BUTTON_TITLE_LOCAL0  = .center,defaultColor:UIColor = CHSIGLE_CHIOSE_CONST.defaultColor  ,selectedColor:UIColor =  CHSIGLE_CHIOSE_CONST.selectedColor,defFont:UIFont = CHSIGLE_CHIOSE_CONST.defFont,selFont:UIFont = CHSIGLE_CHIOSE_CONST.selFont,lineColor:UIColor = CHSIGLE_CHIOSE_CONST.lineColor,lineW:CGFloat = CHSIGLE_CHIOSE_CONST.lineW,lineH:CGFloat = CHSIGLE_CHIOSE_CONST.lineH,itemW:CGFloat? = nil,defIndex:Int = 0){
        self.isShowView = true;
        self.titleArr = titleArr;

    
        self.defaultColor = defaultColor;
        self.selectedColor = selectedColor;
        self.defFont = defFont
        self.selFont = selFont
        self.lineColor = lineColor
        self.lineWith = lineW
        self.lineH = lineH
        self.titleLocal = local
        self.itemW = itemW
        self.defIndex = defIndex
        
    }
    private func initViews(){
        self.isShowView = false;
        selfW = self.frame.size.width;
        selfH = self.frame.size.height;
        print(selfW)
        
    }
    public func btnClickIndexBlockFun(clouse:@escaping(_ index:Int,_ title:String?)-> Void){
        self.clickItemCallBack = clouse
    }
    
 
    
    public func freshItem(index:Int,title:String){
        let btn:UIButton = self.buttonArr[index]
        btn.setTitle(title, for: .normal)
        
        self.freshDataArr(index: index, title: title)
        //刷新linew
        
        self.refreshLineView()
        
    }
           
    
    public func selectIndex(index:Int){
  
    
        let btn:UIButton = self.buttonArr[index]
       
    
         
        self.btnClick(btn: btn)
    
     
       
        
       
    }
      
    
    /*
     刷新数组
     */
    private func freshDataArr(index:Int,title:String){
        
        self.titleArr[index] = title
        print(self.titleArr)
    }

    private  func refreshLineView(){
       
      
        for i  in 0..<self.lineArr.count{
            print(self.lineArr[i])
            var itemW = selfW/CGFloat(self.titleArr.count)
            if self.itemW != nil{
                itemW = self.itemW!
            }else{
                itemW = selfW/CGFloat(self.titleArr.count)
            }
            
            var lineW:CGFloat = 0
            if self.lineWith != 0 {
                lineW = self.lineWith
            }else{
                print("i==",i)
                lineW = self.getWidthWithString(titleString: self.titleArr[i], font: UIFont.systemFont(ofSize: 14))
            
            }
            let lineView:UILabel = self.lineArr[i]
            var line_CenterX:CGFloat = 0
            if self.titleLocal == .left{
                line_CenterX = itemW*CGFloat(i) + lineW/2
            }else if self.titleLocal == .right{
                line_CenterX = itemW*CGFloat(i+1) - lineW/2
            }else{
                line_CenterX = itemW*CGFloat(i) + itemW/2
            }
     
            let line_CenterY:CGFloat = selfH-(self.lineH/CGFloat(2))
            
            
            lineView.frame =  CGRect.init(x: 0, y: selfH - 10 + 2, width: lineW, height: self.lineH)
            lineView.center = CGPoint.init(x: line_CenterX, y: line_CenterY)
        }
    }
     
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        selfW = self.frame.size.width;
        selfH = self.frame.size.height;
        //保证只加载一次
        if (self.isShowView == true) {
            print(self.lineArr.count)
            print(self.titleArr.count)
//            self.lineArr.removeAll()
            showSelectView()
        }
        
        self.isShowView = false;
    }
    
    func showSelectView(){
        for i in 0..<self.titleArr.count {
            let btn:UIButton = UIButton.init(type: .custom)
            
            var itemW = selfW/CGFloat(self.titleArr.count)
            if self.itemW != nil{
                itemW = self.itemW!
            }else{
                itemW = selfW/CGFloat(self.titleArr.count)
            }
            let x = itemW * CGFloat(i)
            let w = itemW
            let h = selfH-10
            btn.frame = CGRect.init(x: x, y: 0, width: w, height: h)
            self .addSubview(btn)
            btn.setTitle(self.titleArr[i], for: .normal)
            btn.setTitleColor(self.defaultColor, for: .normal)
            btn.setTitleColor(self.selectedColor, for: .selected)
          
            btn.titleLabel?.font = self.defFont
            
            if self.titleLocal == .left{
                btn.contentHorizontalAlignment = .left
            } else if self.titleLocal == .center{
                btn.contentHorizontalAlignment = .center
            }else if self.titleLocal == .right{
                btn.contentHorizontalAlignment = .right
            }
       
            if (i==self.defIndex) {
                btn.isSelected = true;
                self.currentBtn = btn;
                self.currentBtn?.titleLabel?.font = self.selFont
            }
            btn.tag = SigleChioseTAG + i
            btn.addTarget(self, action: #selector(btnClick(btn:)), for: .touchUpInside)
            
            self.buttonArr.append(btn)
            
            
            
            let lineView:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: selfH - 10 + 2, width: 0, height: self.lineH))
            


            lineView.backgroundColor = self.lineColor;
            
            lineView.layer.cornerRadius = self.lineH/2;
            lineView.layer.masksToBounds = true;
            
            if (btn.isSelected) {
                lineView.isHidden = false;
            }else{
                lineView.isHidden = true;
            }
            self.addSubview(lineView)
         
            self.lineArr.append(lineView)
            
            self.refreshLineView()
         
        
        }
        
        self.btnIsCanUserClick()
        
   
      
    }
    
    
    func btnIsCanUserClick(){
     
        for i in 0..<self.buttonArr.count{
            let btn = self.buttonArr[i]
            let btnIndex = btn.tag - SigleChioseTAG
            let currentIndex = self.currentBtn!.tag - SigleChioseTAG
            if btnIndex > currentIndex{
                btn.isUserInteractionEnabled = true
            }else{
                btn.isUserInteractionEnabled = true
            }
        }
    }
    
}



//BTN --click
extension CHSingleChioseViewSwift{
    @objc func btnClick(btn:UIButton){
        self.currentBtn?.isSelected = false;
        btn.isSelected = !btn.isSelected;
        self.currentBtn = btn;
        let index = btn.tag - SigleChioseTAG
 

        for i in 0..<self.buttonArr.count{
            let btn = self.buttonArr[i]
            if index == i {
                btn.titleLabel?.font = self.selFont
            }else{
                btn.titleLabel?.font = self.defFont
            }
        }
         
        for i  in 0..<self.lineArr.count{
            let lineView:UILabel = self.lineArr[i]
            if lineView == self.lineArr[index]{
                lineView.isHidden = false
            }else{
                lineView.isHidden = true
            }
        }
      
    
        if (self.clickItemCallBack != nil) {
            self.clickItemCallBack!(index,btn.currentTitle);
        }
    }
}

extension CHSingleChioseViewSwift{
    
    func getWidthWithString(titleString:String,font:UIFont)->CGFloat{
        
        let attrs = [NSAttributedString.Key.font:font]
        let width:CGFloat = titleString.boundingRect(with: CGSize.zero, options: [.usesLineFragmentOrigin], attributes: attrs, context: nil).size.width
        return width
    }
}



